package com.hsg.process;

import android.app.Notification;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;

public class RemoteService extends Service {
    private static final int ID = 10;

    private MyBinder myBinder;
    private ServiceConnection serviceConnection;

    public RemoteService() {
    }

    class MyBinder extends IMyAidlInterface.Stub {

        @Override
        public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {

        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return myBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e("lsn13", "RemoteService onCreate");
        myBinder = new MyBinder();
        serviceConnection = new ServiceConnection();
        startForeground(ID, new Notification());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {//大于18即4.3   版本对应对照参考：https://blog.csdn.net/skycnlr/article/details/79041269
            startService(new Intent(this, InnnerService.class));
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("lsn13", "RemoteService onStartCommand");
        bindService(new Intent(this, LocalService.class), serviceConnection, BIND_AUTO_CREATE);
        return super.onStartCommand(intent, flags, startId);
    }

    class ServiceConnection implements android.content.ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {

        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.e("lsn13", "拉活 LocalService");
            startService(new Intent(RemoteService.this, LocalService.class));
            bindService(new Intent(RemoteService.this, LocalService.class), serviceConnection, BIND_AUTO_CREATE);
        }
    }

    public static class InnnerService extends Service {
        @Override
        public void onCreate() {
            super.onCreate();
            startForeground(ID, new Notification());
            stopSelf();
        }

        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    }
}
